<template>
  <div class="space-y-4 lg:space-y-6">
    <!-- 页面标题 -->
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
      <div>
        <h1 class="text-xl sm:text-2xl font-bold text-gray-900">
          {{ isEdit ? '编辑员工' : '新增员工' }}
        </h1>
        <p class="text-gray-600 mt-1 text-sm sm:text-base">
          {{ isEdit ? '修改员工基本信息和工作信息' : '录入新员工的基本信息和工作信息' }}
        </p>
      </div>
      <router-link to="/employees/list" class="btn-secondary text-sm sm:text-base self-start sm:self-auto">
        <span class="mr-2">←</span>
        返回列表
      </router-link>
    </div>

    <!-- 表单 -->
    <form @submit.prevent="handleSubmit" class="space-y-6">
      <!-- 基本信息 -->
      <div class="card">
        <div class="card-header">
          <h2 class="text-lg font-medium text-gray-900">基本信息</h2>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4 lg:gap-6 xl:gap-8">
          <div>
            <label class="form-label">
              姓名 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model="form.name"
              type="text" 
              class="form-input"
              :class="{ 'border-red-500': errors.name }"
              placeholder="请输入员工姓名"
              maxlength="50"
            />
            <p v-if="errors.name" class="form-error">{{ errors.name }}</p>
          </div>

          <div>
            <label class="form-label">
              性别 <span class="text-red-500">*</span>
            </label>
            <select 
              v-model="form.gender"
              class="form-input"
              :class="{ 'border-red-500': errors.gender }"
            >
              <option value="">请选择性别</option>
              <option value="MALE">男</option>
              <option value="FEMALE">女</option>
            </select>
            <p v-if="errors.gender" class="form-error">{{ errors.gender }}</p>
          </div>

          <div>
            <label class="form-label">
              年龄 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model.number="form.age"
              type="number" 
              class="form-input"
              :class="{ 'border-red-500': errors.age }"
              placeholder="请输入年龄"
              min="16"
              max="70"
            />
            <p v-if="errors.age" class="form-error">{{ errors.age }}</p>
          </div>

          <div>
            <label class="form-label">
              手机号 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model="form.phone"
              type="tel" 
              class="form-input"
              :class="{ 'border-red-500': errors.phone }"
              placeholder="请输入手机号"
              maxlength="11"
              @blur="checkPhoneExists"
            />
            <p v-if="errors.phone" class="form-error">{{ errors.phone }}</p>
          </div>

          <div class="sm:col-span-2 xl:col-span-3 2xl:col-span-4">
            <label class="form-label">
              邮箱 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model="form.email"
              type="email" 
              class="form-input"
              :class="{ 'border-red-500': errors.email }"
              placeholder="请输入邮箱地址"
              @blur="checkEmailExists"
            />
            <p v-if="errors.email" class="form-error">{{ errors.email }}</p>
          </div>
        </div>
      </div>

      <!-- 工作信息 -->
      <div class="card">
        <div class="card-header">
          <h2 class="text-lg font-medium text-gray-900">工作信息</h2>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4 lg:gap-6 xl:gap-8">
          <div>
            <label class="form-label">
              职位 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model="form.position"
              type="text" 
              class="form-input"
              :class="{ 'border-red-500': errors.position }"
              placeholder="请输入职位"
              maxlength="50"
            />
            <p v-if="errors.position" class="form-error">{{ errors.position }}</p>
          </div>

          <div>
            <label class="form-label">
              角色ID <span class="text-red-500">*</span>
            </label>
            <select 
              v-model.number="form.roleId"
              class="form-input"
              :class="{ 'border-red-500': errors.roleId }"
            >
              <option value="">请选择角色</option>
              <option value="1">管理员</option>
              <option value="2">前台</option>
              <option value="3">客房部</option>
              <option value="4">财务</option>
              <option value="5">保安</option>
            </select>
            <p v-if="errors.roleId" class="form-error">{{ errors.roleId }}</p>
          </div>

          <div>
            <label class="form-label">
              入职日期 <span class="text-red-500">*</span>
            </label>
            <input 
              v-model="form.hireDate"
              type="date" 
              class="form-input"
              :class="{ 'border-red-500': errors.hireDate }"
              :max="today"
            />
            <p v-if="errors.hireDate" class="form-error">{{ errors.hireDate }}</p>
          </div>

          <div>
            <label class="form-label">
              状态 <span class="text-red-500">*</span>
            </label>
            <select 
              v-model="form.status"
              class="form-input"
              :class="{ 'border-red-500': errors.status }"
            >
              <option value="">请选择状态</option>
              <option value="ACTIVE">在职</option>
              <option value="INACTIVE">离职</option>
            </select>
            <p v-if="errors.status" class="form-error">{{ errors.status }}</p>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3 sm:gap-4">
        <router-link to="/employees/list" class="btn-secondary text-center">
          取消
        </router-link>
        <button
          type="submit"
          class="btn-primary"
          :disabled="loading || !isFormValid"
        >
          <span v-if="loading" class="mr-2">
            <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
          </span>
          <span v-else class="mr-2">{{ isEdit ? '💾' : '➕' }}</span>
          {{ isEdit ? '保存修改' : '创建员工' }}
        </button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { EmployeeService, type Employee, type EmployeeForm } from '@/api/employee'
import { ApiWrapper, MessageUtils, ValidationUtils } from '@/api/utils'

// 路由
const route = useRoute()
const router = useRouter()

// 状态
const loading = ref(false)
const isEdit = computed(() => !!route.params.id)
const employeeId = computed(() => Number(route.params.id))

// 表单数据
const form = reactive<EmployeeForm>({
  name: '',
  gender: 'MALE',
  age: 25,
  phone: '',
  email: '',
  hireDate: '',
  position: '',
  roleId: 1,
  status: 'ACTIVE'
})

// 表单错误
const errors = reactive<Record<string, string>>({})

// 今天日期（用于限制入职日期）
const today = new Date().toISOString().split('T')[0]

// 表单验证
const isFormValid = computed(() => {
  return Object.keys(errors).length === 0 && 
         form.name && 
         form.gender && 
         form.age && 
         form.phone && 
         form.email && 
         form.position && 
         form.roleId && 
         form.hireDate && 
         form.status
})

// 验证表单
const validateForm = () => {
  const newErrors: Record<string, string> = {}

  // 姓名验证
  if (!form.name.trim()) {
    newErrors.name = '请输入员工姓名'
  } else if (form.name.length < 2) {
    newErrors.name = '姓名至少2个字符'
  }

  // 性别验证
  if (!form.gender) {
    newErrors.gender = '请选择性别'
  }

  // 年龄验证
  if (!form.age) {
    newErrors.age = '请输入年龄'
  } else if (!ValidationUtils.validateAge(form.age)) {
    newErrors.age = '年龄必须在16-70岁之间'
  }

  // 手机号验证
  if (!form.phone) {
    newErrors.phone = '请输入手机号'
  } else if (!ValidationUtils.validatePhone(form.phone)) {
    newErrors.phone = '请输入正确的手机号格式'
  }

  // 邮箱验证
  if (!form.email) {
    newErrors.email = '请输入邮箱地址'
  } else if (!ValidationUtils.validateEmail(form.email)) {
    newErrors.email = '请输入正确的邮箱格式'
  }

  // 职位验证
  if (!form.position.trim()) {
    newErrors.position = '请输入职位'
  }

  // 角色验证
  if (!form.roleId) {
    newErrors.roleId = '请选择角色'
  }

  // 入职日期验证
  if (!form.hireDate) {
    newErrors.hireDate = '请选择入职日期'
  } else if (new Date(form.hireDate) > new Date()) {
    newErrors.hireDate = '入职日期不能晚于今天'
  }

  // 状态验证
  if (!form.status) {
    newErrors.status = '请选择状态'
  }

  // 更新错误状态
  Object.keys(errors).forEach(key => delete errors[key])
  Object.assign(errors, newErrors)

  return Object.keys(newErrors).length === 0
}

// 检查手机号是否存在
const checkPhoneExists = async () => {
  if (!form.phone || !ValidationUtils.validatePhone(form.phone)) {
    return
  }

  try {
    const exists = await EmployeeService.checkPhoneExists(form.phone, isEdit.value ? employeeId.value : undefined)
    if (exists) {
      errors.phone = '该手机号已被其他员工使用'
    } else {
      delete errors.phone
    }
  } catch (error) {
    console.error('Check phone exists error:', error)
  }
}

// 检查邮箱是否存在
const checkEmailExists = async () => {
  if (!form.email || !ValidationUtils.validateEmail(form.email)) {
    return
  }

  try {
    const exists = await EmployeeService.checkEmailExists(form.email, isEdit.value ? employeeId.value : undefined)
    if (exists) {
      errors.email = '该邮箱已被其他员工使用'
    } else {
      delete errors.email
    }
  } catch (error) {
    console.error('Check email exists error:', error)
  }
}

// 加载员工数据（编辑模式）
const loadEmployee = async () => {
  if (!isEdit.value) return

  loading.value = true
  try {
    const employee = await EmployeeService.getEmployeeById(employeeId.value)
    Object.assign(form, {
      name: employee.name,
      gender: employee.gender,
      age: employee.age,
      phone: employee.phone,
      email: employee.email,
      hireDate: employee.hireDate,
      position: employee.position,
      roleId: employee.roleId,
      status: employee.status
    })
  } catch (error) {
    MessageUtils.error('加载员工信息失败')
    router.push('/employees/list')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    MessageUtils.warning('请检查表单填写是否正确')
    return
  }

  const result = await ApiWrapper.request(
    async () => {
      if (isEdit.value) {
        return await EmployeeService.updateEmployee(employeeId.value, form)
      } else {
        return await EmployeeService.createEmployee(form)
      }
    },
    {
      loadingText: isEdit.value ? '保存中...' : '创建中...',
      successMessage: isEdit.value ? '员工信息更新成功' : '员工创建成功'
    }
  )

  if (result) {
    router.push('/employees/list')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  if (isEdit.value) {
    loadEmployee()
  } else {
    // 新增模式，设置默认入职日期为今天
    form.hireDate = today
  }
})
</script>
